package cdkey

import (
	"math/rand"
	"github.com/sqids/sqids-go"
)

type CdKeyData struct {
	MinLen 	int 	// key 的最小长度
	PackId	int 	// 礼包 id
	Seed  	int 	// 随机种子，用来生成兑换码的唯一 id
	Count 	int 	// 兑换码数量

	Keys 	[]string 	// 生成的兑换码列表
	KeyMap 	map[string]int // 兑换码的 map 结构
}

func NewCdKey(minLen int, packId int, count int, seed int) *CdKeyData {
	ck := &CdKeyData{
		MinLen: minLen,
		PackId: packId,
		Seed: seed,
		Count: count,
	}

	ck.Generate(count)

	return ck
}

// 重新生成 count 个兑换码
func (ck *CdKeyData) Generate(count int) {
	s, _ := sqids.NewCustom(sqids.Options{
	    MinLength: &ck.MinLen,
	})
	rd := rand.New(rand.NewSource(int64(ck.Seed)))
	ck.Keys = make([]string, 0, count)
	ck.KeyMap = make(map[string]int)
	for i := 0; i < count; i++ {
		code, _ := s.Encode([]uint64{uint64(ck.PackId), uint64(rd.Int63())})
		ck.Keys = append(ck.Keys, code)
		ck.KeyMap[code] = 1
		// numbers := s.Decode(code)
	}
}

// 检查是否存在 code
func (ck *CdKeyData) CheckCode(code string) bool {
	_, ok := ck.KeyMap[code]
	return ok
}

// 解析兑换码，获得礼包 id 和 兑换码id
func Decode(code string, minLen int) []uint64 {
	s, _ := sqids.NewCustom(sqids.Options{
	    MinLength: &minLen,
	})
	return s.Decode(code)
}